package com.xfcy.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xfcy.blog.common.R;
import com.xfcy.blog.common.constant.RedisConstant;
import com.xfcy.blog.common.constant.SqlConstant;
import com.xfcy.blog.mapper.WebConfigMapper;
import com.xfcy.blog.entity.WebConfig;
import com.xfcy.blog.service.WebConfigService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 网站配置表(WebConfig)表服务实现类
 *
 * @author 晓风残月Lx
 * @since 2023-04-09 11:03:06
 */
@Service("webConfigService")
public class WebConfigServiceImpl extends ServiceImpl<WebConfigMapper, WebConfig> implements WebConfigService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 网站配置列表
     * @return
     */
    @Override
    public R listWebConfig() {
        WebConfig config = baseMapper.selectOne(new QueryWrapper<WebConfig>().last(SqlConstant.LIMIT_ONE));
        return R.success(config);
    }

    /**
     * 修改网络配置
     * @param webConfig
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateWebConfig(WebConfig webConfig) {
        WebConfig config = baseMapper.selectOne(new QueryWrapper<WebConfig>().last(SqlConstant.LIMIT_ONE));

        int update = baseMapper.updateById(webConfig);
        if (update > 0) {
            redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, webConfig.getTouristAvatar());
            redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, webConfig.getAuthorAvatar());
            // 收款码对比
            if (!config.getAliPay().equals(webConfig.getAliPay())) {
                redisTemplate.opsForSet().remove(RedisConstant.DB_FILE_UPLOAD_IMAGES, config.getAliPay());
                redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, webConfig.getAliPay());
            }
            if (!config.getWeixinPay().equals(webConfig.getWeixinPay())) {
                redisTemplate.opsForSet().remove(RedisConstant.DB_FILE_UPLOAD_IMAGES, config.getWeixinPay());
                redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, webConfig.getWeixinPay());
            }
        }
        return R.success();
    }
}


